package com.jt.common.intercepter;

import java.time.LocalTime;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 拦截器执行流程，类似一个执行链
 * */
//定义一个执行链
interface HandlerInterceptor{
        default void before(){};
        default void after(){};
}
interface Handler{
        void processed();//处理业务的方法
}
class  ExcutionChain{
    //一些拦截器(拦截器集合)
    private List<HandlerInterceptor> interceptorList=
            new CopyOnWriteArrayList<>();
        private Handler handler;//业务处理器

        public ExcutionChain(List<HandlerInterceptor> interceptors,Handler handler){
        this.handler=handler;
        this.interceptorList.addAll(interceptors);
    }

        public void execute(){//负责执行业务的方法（例如处理请求）
            //before
            for (int i=0;i<interceptorList.size();i++){
                interceptorList.get(i).before();
            }
            //processed
            handler.processed();
            //after
            for (int i=interceptorList.size()-1;i>=0;i--){
                interceptorList.get(i).after();
            }


        }
}
public class FrameworkTests {//应用层面
    public static void main(String[] args) {
        List<HandlerInterceptor> interceptors=new CopyOnWriteArrayList<>();
        HandlerInterceptor interceptor=new HandlerInterceptor() {
            @Override
            public void before() {
                System.out.println("记录考试开始时间:"+ LocalTime.now());
            }
            @Override
            public void after() {
                System.out.println("记录考试结束时间:"+ LocalTime.now());
            }
        };
        interceptors.add(interceptor);
        //2.创建处理
        Handler handler=new Handler() {
            @Override
            public void processed() {
                System.out.println("同学们开始考试");
            }
        };

        ExcutionChain chain=
                new ExcutionChain(interceptors,handler);
        chain.execute();
    }

}

